package cn.tedu.tmall.admin.mall.service.impl;

import cn.tedu.tmall.admin.mall.dao.persist.repository.ICategoryRepository;
import cn.tedu.tmall.admin.mall.pojo.entity.Category;
import cn.tedu.tmall.admin.mall.pojo.param.CategoryAddNewParam;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryListItemVO;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryStandardVO;
import cn.tedu.tmall.admin.mall.service.ICategoryService;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.vo.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl implements ICategoryService {

    @Value("${tmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private ICategoryRepository categoryRepository;

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {
        // 类别名称必须唯一
        String name = categoryAddNewParam.getName();
        int countByName = categoryRepository.countByName(name);
        if (countByName > 0) {
            String message = "新增类别失败，类别名称已经被占用！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        // 处理depth，并检查父级类别（如果指定了）是否存在
        Integer depth = 1;
        Long parentId = categoryAddNewParam.getParentId();
        CategoryStandardVO parentCategory = null;
        if (parentId != 0) {
            parentCategory = categoryRepository.getStandardById(parentId);
            if (parentCategory == null) {
                String message = "新增类别失败，父级类别不存在！";
                throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
            }
            depth = parentCategory.getDepth() + 1;
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewParam, category);
        category.setDepth(depth);
        category.setIsParent(0);
        int rows = categoryRepository.insert(category);
        if (rows != 1) {
            String message = "新增类别失败，服务器忙，请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        // 可能需要将父级类别的isParent从0改为1
        if (parentCategory != null && parentCategory.getIsParent() == 0) {
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            rows = categoryRepository.updateById(updateParentCategory);
            if (rows != 1) {
                String message = "新增类别失败，服务器忙，请稍后再试！";
                throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
            }
        }
    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {
        System.out.println("开始执行：根据ID查询类别详情");
        CategoryStandardVO queryResult = categoryRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "查询类别详情失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<CategoryListItemVO> listByParent(Long parentId, Integer pageNum) {
        return categoryRepository.listByParent(parentId, pageNum, defaultQueryPageSize);
    }

    @Override
    public PageData<CategoryListItemVO> listByParent(Long parentId, Integer pageNum, Integer pageSize) {
        return categoryRepository.listByParent(parentId, pageNum, pageSize);
    }

}